package com.cjl.algorithm.tree;

public class TreeNode {
    private Integer element;
    private TreeNode left;
    private TreeNode right;

    public TreeNode() {
    }

    public TreeNode(Integer element, TreeNode left, TreeNode right) {
        this.element = element;
        this.left = left;
        this.right = right;
    }

    public Object getElement() {
        return element;
    }

    public void setElement(Integer element) {
        this.element = element;
    }

    public TreeNode getLeft() {
        return left;
    }

    public void setLeft(TreeNode left) {
        this.left = left;
    }

    public TreeNode getRight() {
        return right;
    }

    public void setRight(TreeNode right) {
        this.right = right;
    }

    public TreeNode find(Integer target,TreeNode treeNode){
        if (treeNode == null){
            return null;
        }
        if (target < treeNode.element){
            return find(target,treeNode.left);
        }else if (target > treeNode.element){
            return find(target,treeNode.right);
        }else {
            return treeNode;
        }
    }

    public TreeNode findMin(TreeNode treeNode){
        if (treeNode == null){
            return null;
        }
        if (treeNode.left != null){
            return findMin(treeNode.left);
        }else {
            return treeNode;
        }
    }

    public TreeNode findMax(TreeNode treeNode){
        if (treeNode == null){
            return null;
        }
        if (treeNode.right != null){
            return findMax(treeNode.right);
        }else {
            return treeNode;
        }
    }

    public TreeNode insert(Integer integer,TreeNode treeNode){
        if (treeNode == null){
            return new TreeNode(integer,null,null);
        }
        if (integer < treeNode.element){
            if (treeNode.left == null){
                TreeNode left = new TreeNode(integer,null,null);
                treeNode.left = left;
                return treeNode.left;
            }else {
                return insert(integer,treeNode.left);
            }
        }else if (integer > treeNode.element){
            if (treeNode.right == null){
                TreeNode right = new TreeNode(integer,null,null);
                treeNode.right = right;
                return treeNode.right;
            }else {
                return insert(integer,treeNode.right);
            }
        }else {
            return treeNode;
        }
    }

    public void printTreeNode(TreeNode treeNode){
        if (treeNode == null){
            return;
        }
        printTreeNode(treeNode.left);
        System.out.println(treeNode.getElement());
        printTreeNode(treeNode.right);
    }
}
